package cool.mtc.minghe.service.service.security.impl;

import cool.mtc.minghe.service.manager.cache.CacheManager;
import cool.mtc.minghe.service.manager.sys.user.UserManager;
import cool.mtc.minghe.service.mapper.security.SecurityMapper;
import cool.mtc.security.data.model.UserDetails;
import cool.mtc.security.service.SecurityService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 明河
 */
@Slf4j
@Service(value = "securityService")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SecurityServiceImpl implements SecurityService {
    private final SecurityMapper securityMapper;
    private final CacheManager cacheManager;
    private final UserManager userManager;

    @Override
    public boolean isTokenInAllowList(String token) {
        return cacheManager.isTokenInAllowList(token);
    }

    @Override
    public void saveTokenToAllowList(String token, UserDetails user) {
        cacheManager.saveTokenToAllowList(token, user);
    }

    @Override
    public void removeTokenFromAllowList(String token) {
        cacheManager.removeTokenFromAllowList(token);
    }

    @Override
    public UserDetails loadByUsernameAndAuthType(String username, String authType) {
        UserDetails user = securityMapper.getByIdentifierAndAuthType(username, authType);
        this.handleUserDetails(user);
        return user;
    }

    private void handleUserDetails(UserDetails user) {
        if (null == user) {
            return;
        }
        long userId = Long.parseLong(user.getUserId().toString());
        // 默认所属单位
        Long orgId = this.getDefaultOrgId(userId);
        if (null == orgId) {
            return;
        }
        user.setOrgId(orgId);
        // 权限列表
        List<String> permissionList = userManager.listPermissionByUserIdAndOrgId(userId, orgId);
        user.setPermissionList(permissionList);
    }

    @Override
    public UserDetails loadByUserIdAndOrgIdAndAuthType(Object userIdObj, Object orgIdObj, String authType) {
        long userId = Long.parseLong(userIdObj.toString());
        long orgId = Long.parseLong(orgIdObj.toString());
        return userManager.getUserDetailsByUserIdAndOrgIdAndAuthType(userId, orgId, authType);
    }

    /**
     * 获取用户所属默认单位
     * 因用户可能同时属于多个单位，操作要求只能同时属于一个单位
     * 获取id最小的单位
     */
    private Long getDefaultOrgId(long userId) {
        return securityMapper.getDefaultOrgIdByUserId(userId);
    }
}
